package main

import (
	"fmt"
	"net"
	"os"
)

func main() {
	if len(os.Args) != 2 {
		fmt.Fprintf(os.Stderr, "Usage: %s host:port", os.Args[0])
		os.Exit(1)
	}
	service := os.Args[1]
	udpAddr, err := net.ResolveUDPAddr("udp4", service)
	checkError(err)
	conn, err := net.DialUDP("udp", nil, udpAddr)
	checkError(err)
	_, err = conn.Write([]byte("yuntongxunyt[client_id:5]"))
	checkError(err)
	//var buf [512]byte
	//n, err := conn.Read(buf[0:])
	//checkError(err)
	//fmt.Println(string(buf[0:n]))
	messages := make(chan string, 10)
	Handler(conn, messages)
	os.Exit(0)
}
func checkError(err error) {
	if err != nil {
		fmt.Fprintf(os.Stderr, "Fatal error ", err.Error())
		os.Exit(1)
	}
}

func Handler(conn net.Conn, messages chan string) {
	fmt.Println("connection is connected to ...", conn.RemoteAddr().String())
	buf := make([]byte, 8096)
	for {
		lenght, err := conn.Read(buf)
		checkError(err)
		if lenght > 0 {
			buf[lenght] = 0
		}
		fmt.Println(conn.RemoteAddr().String(), ":", string(buf[0:lenght]), "LIDE", lenght)
		reciveStr := string(buf[0:lenght])
		messages <- reciveStr

	}

}
